package com.resou.reader.mine.vipcenter.vipCenter;

import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.ArrayMap;
import android.widget.TextView;

import com.resou.reader.R;
import com.resou.reader.api.ApiImp;
import com.resou.reader.api.entry.BookContentBean;
import com.resou.reader.api.entry.MetMealBean;
import com.resou.reader.api.entry.MonthlyVipBean;
import com.resou.reader.api.entry.PayResultBean;
import com.resou.reader.api.entry.PrivilegeBean;
import com.resou.reader.api.entry.Result;
import com.resou.reader.api.entry.ResultList;
import com.resou.reader.api.entry.UserInfoBean;
import com.resou.reader.api.entry.WXPayBean;
import com.resou.reader.api.service.PayService;
import com.resou.reader.api.service.UserService;
import com.resou.reader.api.service.VipService;
import com.resou.reader.base.BaseView;
import com.resou.reader.base.ResouBasePresenter;
import com.resou.reader.data.vip.model.VipPrivilege;
import com.resou.reader.mine.IView.UserInstance;
import com.resou.reader.mine.paycenter.AliPay;
import com.resou.reader.paycenter.v.IVIPCenterView;
import com.resou.reader.utils.DateUtils;
import com.resou.reader.utils.DeviceUtils;
import com.resou.reader.utils.eventbus.MessageEvent;
import com.resou.reader.utils.log.LogUtil;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Author: 萤火虫
 * E-mail:  Allensuns@163.com
 * Description: 会员中心
 * CreateTime: 2019-04 -16
 **/
public class VipCenterPresenter extends ResouBasePresenter<IVipCenterContract.IVipCenterView> implements IVipCenterContract.IVipCenterPresenter {
    UserService userService;
    PayService payService;
    VipService vipService;
    List<VipPrivilege.PackageDataBean> listMetMeal;

    public VipCenterPresenter(IVipCenterContract.IVipCenterView view) {
        super(view);
        userService = ApiImp.getInstance().getService(UserService.class);
        payService = ApiImp.getInstance().getService(PayService.class);
        vipService = ApiImp.getInstance().getService(VipService.class);

    }

    @Override
    public void quearUserInfo() {
        mView.showProgress();
        userService.getUserInfo(UserInstance.getToken())
                .subscribeOn(getIOSchedulers())
                .observeOn(getMainSchedulers())
                .subscribe(new Observer<Result<UserInfoBean>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addCompositeDisposable(d);
                    }

                    @Override
                    public void onNext(Result<UserInfoBean> userInfoBeanResult) {
                        if (userInfoBeanResult.getData() != null && userInfoBeanResult.getData().getU() != null) {
                            UserInstance.saveUserInfo(userInfoBeanResult.getData().getU());
                            mView.showUserInfo(userInfoBeanResult.getData());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.showError(e);
                    }

                    @Override
                    public void onComplete() {
                        mView.showContent();
                    }
                });
    }

    /**
     * 特权数据
     *
     * @return
     */
    @Override
    public void quearPrivilege() {
        payService.quearPrivilege(UserInstance.getToken()).subscribeOn(getIOSchedulers())
                .observeOn(getMainSchedulers())
                .subscribe(new Consumer<Result<VipPrivilege>>() {
                    @Override
                    public void accept(Result<VipPrivilege> privilegeBeanResult) throws Exception {
                        mView.showPrivilege(privilegeBeanResult.getData().getPrivilege_data());
                        mView.showCoupont(privilegeBeanResult.getData().getPackage_data());
                        listMetMeal = privilegeBeanResult.getData().getPackage_data();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        mView.showError(throwable);
                    }
                });
    }

    @Override
    public List<VipPrivilege.PackageDataBean> quearMetMeal() {
//        List<MetMealBean> list = new ArrayList<>();
        /**
         * 普通数据
         */
//        list.add(new MetMealBean("3天\n体验", "￥3", "3天体验会员，海量包月书籍免费读", "￥1", "", false));
//        list.add(new MetMealBean("1个月", "￥12", "自动续费1个月，另赠送", "￥8", "200热券", false));
//        list.add(new MetMealBean("3个月", "￥40", "自动续费3个月，另赠送", "￥28", "￥500热券", false));
//        list.add(new MetMealBean("6个月", "￥73", "自动续费6个月，另赠送", "￥60", "￥1000热券", false));
//        list.add(new MetMealBean("12个月", "￥128", "自动续费12个月，另赠送", "￥108", "￥1500热券", true));

        return listMetMeal;
    }

    @Override
    public synchronized void quearRemoteMetMeal() {
        mView.showProgress();
//        /**
//         * 免费专题数据
//         */
//
//        payService.quearCoupon(UserInstance.getToken())
//                .subscribeOn(getIOSchedulers())
//                .observeOn(getMainSchedulers())
//                .subscribe(new Observer<ResultList<MetMealBean>>() {
//                    @Override
//                    public void onSubscribe(Disposable d) {
//                        addCompositeDisposable(d);
//                    }
//
//                    @Override
//                    public void onNext(ResultList<MetMealBean> metMealBeanResult) {
//                        if (metMealBeanResult.getData() != null) {
//                            listMetMeal = metMealBeanResult.getData();
//                            mView.showCoupont(listMetMeal);
//                        }
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//                        mView.showError(e);
//                    }
//
//                    @Override
//                    public void onComplete() {
//                        mView.showContent();
//                    }
//                });
    }

    @Override
    public synchronized List<VipPrivilege.PackageDataBean> calcMetMealCheck(List<VipPrivilege.PackageDataBean> list, int pos) {
        for (int i = 0; i < list.size(); i++) {
            //如果已经开通VIP  则隐藏7天免费
            list.get(i).setCheck(false);
            if (i == pos) {
                list.get(i)
                        .setCheck(true);
            }
        }
        return list;
    }


    @Override
    public String getVIPDes(int state) {
        switch (state) {
            case 2:
                return "已开通包月VIP";
            case 3:
                return "您的包月VIP已过期";
            case 0:
                return "未开通包月VIP";
        }
        return "未开通包月VIP";
    }

    @Override
    public void setTimeColor(TextView textView, String text, String sourceText) {
        SpannableStringBuilder sbb = new SpannableStringBuilder(text);
        for (int i = 0; i < text.length(); i++) {
            String temp = text.substring(i, i + 1);
            if (sourceText.contains(temp)) {
                sbb.setSpan(new ForegroundColorSpan(textView.getResources().getColor(R.color.theme_color)),
                        i, i + 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);//Color.parseColor("#ffc36a")
            }
        }
        textView.setText(sbb);
    }

    /**
     * 更新VIP状态
     */
    @Override
    public void updataVIPState() {
        payService.saveVIPRecord(UserInstance.getToken())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Result<String>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addCompositeDisposable(d);
                    }

                    @Override
                    public void onNext(Result<String> aliPay) {
                        if (aliPay.getCode() == 0) {
                            LogUtil.d("tag", aliPay.getMsg() + "");
                            quearUserInfo();
                            EventBus.getDefault().post(new MessageEvent());
                            EventBus.getDefault().post(new BookContentBean());
                            mView.goPaySuccessPage();
                        } else {
                            LogUtil.d("tag", aliPay.getData());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.showError(e);
                    }

                    @Override
                    public void onComplete() {
                        mView.showContent();
                    }
                });
    }

    @Override
    public void quaerAliPayOrderInfo(String price, String id, String coupon) {
        mView.showProgress();
        String endTime = DateUtils.getVIPendTime(id);
        payService.aliPayVipApp(UserInstance.getToken(), price, endTime, coupon)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<AliPay>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addCompositeDisposable(d);
                    }

                    @Override
                    public void onNext(AliPay aliPay) {
                        mView.showAliPayOrder(aliPay.getUrl());
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.showError(e);
                    }

                    @Override
                    public void onComplete() {
                        mView.showContent();
                    }
                });
    }

    @Override
    public void quaerWXPayOrderInfo(String price, String id, String coupon) {
        mView.showProgress();
        String title = "包月VIP";
        String endTime = DateUtils.getVIPendTime(id);
        payService.wxVIPPayAndroid(UserInstance.getToken(), price, title,
                DeviceUtils.getIMEI(mView.getViewContext()), endTime, coupon)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Result<WXPayBean>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addCompositeDisposable(d);
                    }

                    @Override
                    public void onNext(Result<WXPayBean> result) {
                        if (result == null) {
                            return;
                        }
                        mView.showWXPayOrder(result.getData());
                        //统计用户充值哪个金额比较多
                        Map<String, String> map = new ArrayMap<>();
                        map.put("type", title);
                        map.put("amount", price);
                        MobclickAgent.onEvent(mView.getViewContext(), "pay_amount", map);
                        map.clear();
                        map.put("充值说明", title);
                        map.put("充值金额", price);
                        MobclickAgent.onEvent(mView.getViewContext(), "pay_amount1", map);
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.showError(e);
                    }

                    @Override
                    public void onComplete() {
                        mView.showContent();
                    }
                });
    }

}
